package com.ty.service.imple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ty.dao.BaseDaoI;
import com.ty.entity.SysAdmin;
import com.ty.entity.SysRole;
import com.ty.entity.SysUserRole;
import com.ty.service.RoleService;
import com.ty.util.Pager;

@Service
public class RoleServiceImple implements RoleService {

	@Autowired
	private BaseDaoI<SysRole> dao;
	@Autowired
	private BaseDaoI<SysUserRole> userRoleDao;
	 
	@Override
	public Pager selectByPager(int pageNum, int pageSize, SysRole role) {
		//查询条件
		Map<String,Object> params=new HashMap<>();
				
				
		String hql="from SysRole o";
		String countHql="select count(o) "+hql;
		
		String where=" where 1=1 ";
		
		if(role!=null&&role.getName()!=null&&!"".equals(role.getName())) {
			where+=" and o.name=:name";
			params.put("name", role.getName());
		}
		
		hql+=where;
		countHql+=where;
		
		Pager page=new Pager();
		//获取总行数
		page.setTotalCount(dao.count(countHql,params).intValue());
		//获取总页数
		page.setPageSize(pageSize);
		page.setCurrentPageIndex(pageNum);
		//分页查询
		List<SysRole> list= dao.find(hql, params, page.getCurrentPageIndex(), page.getPageSize());
		page.setData(list);
		
		return page;
	}

	@Override
	public boolean deleteById(Long id) {
		try {
			SysRole role = getById(id);
			dao.delete(role);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean updateByObj(SysRole role) {
		try {
			dao.update(role);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public SysRole getById(Long id) {
		return dao.get(SysRole.class, id);
	}

	@Override
	public boolean deleteBatch(String ids) {
		try {
			String idArrays[] = ids.split(",");
			for (String id : idArrays) {
				this.deleteById(Long.valueOf(id));
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean saveObject(SysRole role) {
		try {
			dao.save(role);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public List<SysRole> selectAll(Long userId) {
		String hql="from SysRole ";
		List<SysRole> list= dao.find(hql);
		for (SysRole sysRole : list) {
			String countHql="select count(o) from SysUserRole o where o.sysAdmin.id="+userId+" and o.sysRole.id="+sysRole.getId();
			long count= userRoleDao.count(countHql);
			sysRole.setChecked(count>=1?true:false);
		}
		return list;
	}

}
